package com.probox.common.entity.service.wechat.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.probox.common.core.constant.CachePrefix;
import com.probox.common.core.domain.R;
import com.probox.common.core.enums.*;
import com.probox.common.core.exception.WechatException;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.core.utils.WechatQrCode.WeixinQrCodeUtil;
import com.probox.common.redis.service.RedisService;
import com.probox.common.entity.domain.wechat.AppletCodeManage.AppletCodeAudit;
import com.probox.common.entity.domain.wechat.AppletCodeManage.CodeTemplate;
import com.probox.common.entity.domain.wechat.AppletCodeManage.OrdinaryTemplate;
import com.probox.common.entity.domain.wechat.AppletCodeManage.StandardTemplate;
import com.probox.common.entity.domain.wechat.AppletInfo.*;
import com.probox.common.entity.domain.wechat.EnterpriseInfo;
import com.probox.common.entity.domain.wechat.WechatAppletInfo;
import com.probox.common.entity.domain.wechat.WechatAuthorizationInfo;
import com.probox.common.entity.domain.wechat.WechatCommonRetuen;
import com.probox.common.entity.mapper.wechat.WechatAppletInfoMapper;
import com.probox.common.entity.mapper.wechat.WechatAuthorizationInfoMapper;
import com.probox.common.entity.mapper.wechat.WechatCommonRetuenMapper;
import com.probox.common.entity.mapper.wechat.WechatFuncInfoMapper;
import com.probox.platform.api.RemotePlatformService;
import com.probox.platform.api.domain.PlatformInfoVo;
import com.probox.wechat.api.domain.WechatAuthorizationInfoVo;
import com.probox.wechat.api.domain.WxQrCode;
import com.probox.common.entity.domain.wechat.AppletCategory.CanSetCategoryInfo;
import com.probox.common.entity.domain.wechat.AppletCategory.Category;
import com.probox.common.entity.domain.wechat.AppletCategory.CategoryInfo;
import com.probox.common.entity.domain.wechat.AppletCategory.Certicates;
import com.probox.common.entity.service.wechat.IWechatAuthorizationInfoService;
import com.probox.common.entity.service.wechat.WechatMiniService;
import com.probox.common.entity.service.wechat.WechatPlatformService;
import com.probox.common.entity.domain.wechat.vo.ApiQueryAuthVo;
import com.probox.common.entity.domain.wechat.vo.AuthorizationInfoVo;
import com.probox.common.entity.domain.wechat.vo.CanSetCategoryInfoVo;
import com.probox.common.entity.domain.wechat.vo.CodeTemplateVo;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.TimeUnit;


@Service
public class WechatMiniServiceImpl  implements WechatMiniService {
    @Autowired
    private WechatPlatformService wechatPlatformService;

    //公共返回参数mapper
    @Autowired
    private WechatCommonRetuenMapper wechatCommonRetuenMapper;

    //授权信息对象Mapper
    @Autowired
    private WechatAuthorizationInfoMapper authorizationInfoMapper;

    //小程序基本信息返回参数对象mapper
    @Autowired
    private WechatAppletInfoMapper wechatAppletInfoMapper;

    @Autowired
    private IWechatAuthorizationInfoService wechatAuthorizationInfoService;


    //微信权限集
    @Autowired
    private WechatFuncInfoMapper wechatFuncInfoMapper;

    @Autowired
    private RedisService redisService;

    @Autowired
    private RemotePlatformService remotePlatformService;

    private RestTemplate restTemplate;


    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    //第三方服务访问token
    private static String component_access_token = "";

    //h5授权信息
    private static final String WECHAT_H5_AUTHORIZATION = CachePrefix.PRE_GLOABLE + "WECHAT_H5_AUTHORIZATION";

    /**
     * 快速注册小程序
     */
    private final static String create_fastregisterweapp = "https://api.weixin.qq.com/cgi-bin/component/fastregisterweapp?action=create&component_access_token=";
    private String unbindTestRetuen;

    @Override
    public String registerApplet(EnterpriseInfo enterpriseInfo) {
        if (StringUtils.isEmpty(enterpriseInfo)){
            throw new WechatException("企业信息不能为空");
        }
//        Map<String,Object> param = new HashMap<>();
//        param.put("name",enterpriseInfo.getName());
//        param.put("code",enterpriseInfo.getCode());
//        param.put("code_type",enterpriseInfo.getCodeType());
//        param.put("legal_persona_wechat",enterpriseInfo.getLegalPersonaWechat());
//        param.put("legal_persona_name",enterpriseInfo.getLegalPersonaName());
//        EnterpriseInfoVo enterpriseInfoVo = new EnterpriseInfoVo(enterpriseInfo.getName(),enterpriseInfo.getCode(),enterpriseInfo.getCodeType(),enterpriseInfo.getLegalPersonaWechat(),enterpriseInfo.getLegalPersonaName());
        String paramJson = "{\"name\": \""+enterpriseInfo.getName()+"\",\"code\": \""+enterpriseInfo.getCode()+"\"," +
                "\"code_type\": "+enterpriseInfo.getCodeType()+",\"legal_persona_wechat\": \""+enterpriseInfo.getLegalPersonaWechat()+"\"," +"\"legal_persona_name\": \""+enterpriseInfo.getLegalPersonaName()+"\"" +
                ",\"component_phone\": \""+""+"\"}";
        logger.info("快速注册小程序请求参数为=>"+paramJson);
        String fastregisterweappJson = HttpUtil.post(create_fastregisterweapp+wechatPlatformService.getApiComponentToken(), paramJson);
        JSONObject obj = JSONObject.parseObject(fastregisterweappJson);
        String errcode = obj.getString("errcode");
        String errmsg =  obj.getString("errmsg");
        WechatCommonRetuen commonRetuen = new WechatCommonRetuen();
        commonRetuen.setErrcode(Long.parseLong(errcode));
        commonRetuen.setErrmsg( errmsg);
        wechatCommonRetuenMapper.insert(commonRetuen);
        if (!StringUtils.isEmpty(commonRetuen)){
            logger.info("成功存入数据库,返回参数为=>"+commonRetuen);
        }else {
            logger.info("快速注册企业小程序,存入数据库失败");
        }
        return obj.getString("errcode");
    }

    /**
     * 查询创建任务状态
     */
    private final static String find_fastregisterweapp = "https://api.weixin.qq.com/cgi-bin/component/fastregisterweapp?action=search&component_access_token=";
    @Override
    public String findCreateTask(EnterpriseInfo enterpriseInfo) {
        if (StringUtils.isEmpty(enterpriseInfo)){
            throw new WechatException("企业信息不能为空");
        }
        Map<String,Object> param = new HashMap<>();
        param.put("name",enterpriseInfo.getName());
        param.put("legal_persona_wechat",enterpriseInfo.getLegalPersonaWechat());
        param.put("legal_persona_name",enterpriseInfo.getLegalPersonaName());
        logger.info("请求参数为=>"+param);
        String findFastregisterweappJson = HttpUtil.post(find_fastregisterweapp+wechatPlatformService.getApiComponentToken(), JSON.toJSONString(param));
        JSONObject obj = JSONObject.parseObject(findFastregisterweappJson);
        WechatCommonRetuen commonRetuen = new WechatCommonRetuen();
        commonRetuen.setErrcode(Long.parseLong(obj.getString("errcode")));
        commonRetuen.setErrmsg( obj.getString("errmsg"));
        wechatCommonRetuenMapper.insert(commonRetuen);
        if (!StringUtils.isEmpty(commonRetuen)){
            logger.info("成功存入数据库,返回参数为=>"+commonRetuen);
        }else {
            logger.info("查询创建任务状态,存入数据库失败");
        }
        return findFastregisterweappJson;
    }

    @Override
    public String ToAuthorization(String indexUrl,String authorizationInfo) throws IOException {
//        WechatAuthorizationInfo wechatAuthorizationInfo = getAuthorizerAppid(authorizationType);
        //查询当前平台的公众号
//        QueryWrapper<WechatAuthorizationInfo> authorizationInfoQueryWrapper = new QueryWrapper<>();
//        authorizationInfoQueryWrapper.eq("PLATFORM_ID",SecurityUtils.getPlatformId());
//        authorizationInfoQueryWrapper.eq("AUTHORIZER_TYPE","allwork");
//        authorizationInfoMapper.selectOne(appid);
//        WechatAuthorizationInfo wechatAuthorizationInfo = authorizationInfoMapper.selectById(appid);
//        if (wechatAuthorizationInfo == null){
//            return "-1";
//        }
        ApiQueryAuthVo vo = JSON.parseObject(authorizationInfo, ApiQueryAuthVo.class);
        AuthorizationInfoVo ai = vo.getAuthorization_info();
        String redirect_uri = URLEncoder.encode("https://console.yooruan.com/api/prod-api/wechat/applet/skipIndex?url="+indexUrl+"&authorizationToken="+ai.getAuthorizer_access_token()+"&platformid="+SecurityUtils.getPlatformId()+"&allworkAppid="+ai.getAuthorizer_appid()+"&bindRefreshToken="+ai.getAuthorizer_refresh_token(),"utf-8");
        String url = "https://mp.weixin.qq.com/cgi-bin/fastregisterauth?appid="+ai.getAuthorizer_appid()+"&component_appid="+WechatPlatformService.appId+"&copy_wx_verify=1&redirect_uri="+redirect_uri;
        return url;
    }


    /**
     * 从第三方平台跳转至微信公众平台授权注册页面
     */
    private final static String regiterApi = "https://api.weixin.qq.com/cgi-bin/account/fastregister?access_token=";
    @Override
    public String speedinessRegiter(String ticket,String authorizationToken,String platformid,String allworkAppid,String bindRefreshToken) {
        //查询授权信息
//        String key = CachePrefix.PLATFORM_AUTHORIZER_APPID+platformid+"_"+authorizationType;
//        Object authorizerappid = redisService.getCacheObject(key);
//        WechatAuthorizationInfo wechatAuthorizationInfo = authorizationInfoMapper.selectById(String.valueOf(authorizerappid));
//        if (authorizerappid != null){
//            if("-1".equals(wechatAuthorizationInfo.getDataStatus())){
//                throw new WechatException("请授权后重试");
//            }
//        }else {
//            wechatAuthorizationInfo = PlatformRefreshToken(authorizationType,platformid);
//        }
        Map<String,Object> param = new HashMap<>();
        param.put("ticket",ticket);
        String regiterApiJson =  HttpUtil.post(regiterApi+ authorizationToken, JSON.toJSONString(param));
        JSONObject obj = JSONObject.parseObject(regiterApiJson);
        String errcode =  obj.getString("errcode");
        String errmsg =  obj.getString("errmsg");
        String appid =  obj.getString("appid");
        String authorization_code =  obj.getString("authorization_code");
        String is_wx_verify_succ =  obj.getString("is_wx_verify_succ");
        String is_link_succ =  obj.getString("is_link_succ");
        logger.info("快速注册小程序返回值=>"+errcode+"appid为:"+appid+",复用公众号微信认证小程序是否成功:"+is_wx_verify_succ+",小程序是否和公众号关联成功"+is_link_succ);
        if("0".equals(errcode)){
            String apiQueryAuth = wechatPlatformService.getApi_query_auth(authorization_code, "3600",platformid, WechatAuthorizationTypeEnum.applet.getKey(),"0",allworkAppid,bindRefreshToken);
            logger.info("绑定授权信息返回"+apiQueryAuth);
        }
        WechatCommonRetuen commonRetuen = new WechatCommonRetuen();
        commonRetuen.setErrcode(Long.parseLong(errcode));
        commonRetuen.setErrmsg(errmsg);
        HashMap retuenMap = new HashMap();
        retuenMap.put("appid",appid);
        retuenMap.put("authorization_code",authorization_code);
        retuenMap.put("is_wx_verify_succ",is_wx_verify_succ);
        retuenMap.put("is_link_succ",is_link_succ);
        JSONObject jsonObj=new JSONObject(retuenMap);
        commonRetuen.setRetuenParameter(String.valueOf(jsonObj));
        wechatCommonRetuenMapper.insert(commonRetuen);
        if (!StringUtils.isEmpty(commonRetuen)){
            logger.info("成功存入数据库=>"+commonRetuen);
        }else {
            logger.info("第三方平台调用快速注册 API 完成注册,存入数据库失败");
        }
        return errcode;
    }

    /**
     * 跳转至微信公众平台指定换绑页面
     * @return
     */
    @Override
    public String IntieAdmin(String indexUrl,String authorizationType) throws IOException{
        WechatAuthorizationInfo wechatAuthorizationInfo = getAuthorizerAppid(authorizationType);
        String redirect_uri = URLEncoder.encode("https://console.yooruan.com/api/prod-api/wechat/applet/skipIntie?bindAllworkAppid="+wechatAuthorizationInfo.getBindAllorkappid()+"&appid="+wechatAuthorizationInfo.getAuthorizerAppid()+"&bindRefreshToken="+wechatAuthorizationInfo.getAuthorizerRefreshToken(),"utf-8");
        String url = "https://mp.weixin.qq.com/wxopen/componentrebindadmin?appid="+wechatAuthorizationInfo.getBindAllorkappid()+"&component_appid="+WechatPlatformService.appId+"&redirect_uri="+redirect_uri;
        return url;
    }

    /**
     * 换绑小程序管理员接口
     * @param taskid
     * @return
     */
    private final static String IntieRegiterApi = "https://api.weixin.qq.com/cgi-bin/account/componentrebindadmin?access_token=";
    @Override
    public String IntieRegiter(String taskid,String bindAllworkAppid,String bindRefreshToken,String appid) {
        //查询授权信息
        AuthorizationInfoVo authorizationInfoVo = redisService.getCacheObject(CachePrefix.WECHAT_BIND_AUTHORIZERINDO+bindAllworkAppid);
        if(ObjectUtil.isEmpty(authorizationInfoVo)){
            authorizationInfoVo = wechatPlatformService.getApi_authorizer_token(wechatPlatformService.getApiComponentToken(),bindAllworkAppid,bindRefreshToken);
        }
        Map<String,Object> param = new HashMap<>();
        param.put("taskid",taskid);
        String IntieRegiterJson =  HttpUtil.post(IntieRegiterApi+ authorizationInfoVo.getAuthorizer_access_token(), JSON.toJSONString(param));
        JSONObject obj = JSONObject.parseObject(IntieRegiterJson);
        String code = obj.getString("errcode");
        if("0".equals(code)){
            UpdateWrapper<WechatAuthorizationInfo> authorizationInfoUpdateWrapper = new UpdateWrapper<>();
            authorizationInfoUpdateWrapper.eq("AUTHORIZER_APPID",appid);
            authorizationInfoUpdateWrapper.set("IS_EXCHANGEBIND", WechatExchangeBindStatusEnum.echangeBind.getKey());
            wechatAuthorizationInfoService.update(authorizationInfoUpdateWrapper);
        }
        return code;
    }


    /**
     * 获取授权方信息
     */
    private final static String apiGetAuthorizerInfo = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token=";
    @Override
    public HashMap getAuthorizerInfo(String authorizationType,String platformid) {
        String status = "1";
        if (StringUtils.isEmpty(platformid)){
            status = "0";
            platformid  = String.valueOf(SecurityUtils.getPlatformId());
        }
        logger.info("查询平台为:"+platformid+",类型为:"+authorizationType+"的授权信息");
        String key = CachePrefix.PLATFORM_AUTHORIZER_APPID+platformid+"_"+authorizationType;
        Object authorizerappid = redisService.getCacheObject(key);
        WechatAuthorizationInfo wechatAuthorizationInfo = authorizationInfoMapper.selectById(String.valueOf(authorizerappid));
        if (authorizerappid != null){
            if("-1".equals(wechatAuthorizationInfo.getDataStatus())){
                throw new WechatException("请授权后重试");
            }
        }else {
            wechatAuthorizationInfo = PlatformRefreshToken(authorizationType,platformid);
        }
        Map<String,Object> param = new HashMap<>();
        param.put("component_appid",WechatPlatformService.appId);
        param.put("authorizer_appid",wechatAuthorizationInfo.getAuthorizerAppid());
        String AuthorizerInfoJson = HttpUtil.post(apiGetAuthorizerInfo+wechatPlatformService.getApiComponentToken(), JSON.toJSONString(param));
        JSONObject obj = JSONObject.parseObject(AuthorizerInfoJson);
        logger.info("获取授权信息返回=>"+obj);
        HashMap authorizerInfoMap = new HashMap();
        if ("61003".equals(obj.getString("errcode"))){
            QueryWrapper<WechatAuthorizationInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("AUTHORIZER_APPID",wechatAuthorizationInfo.getAuthorizerAppid());
            WechatAuthorizationInfo AuthorizationInfo = authorizationInfoMapper.selectOne(queryWrapper);
            AuthorizationInfo.setDataStatus(DataStatus.delete.getKey());
            authorizationInfoMapper.updateById(AuthorizationInfo);
            authorizerInfoMap.put("authorizerStatus",-1);
        }
        if (!StringUtils.isEmpty(obj.getString("authorizer_info"))){
            String authorizer_info =  obj.getString("authorizer_info");
            JSONObject authorizerInfo = JSONObject.parseObject(authorizer_info);
            //func_info 权限集
            String authorization_info =  obj.getString("authorization_info");
            JSONObject authorizationInfo = JSONObject.parseObject(authorization_info);
            String verifyTypeInfostr = authorizerInfo.getString("verify_type_info");
            JSONObject verifyTypeInfoobj = JSONObject.parseObject(verifyTypeInfostr);
            authorizerInfoMap.put("verifyTypeInfo",verifyTypeInfoobj.get("id"));
            authorizerInfoMap.put("nickName",authorizerInfo.getString("nick_name"));
            String headImg = authorizerInfo.getString("head_img");
            logger.info("授权信息头像信息:"+headImg);
            if(!StringUtils.isEmpty(headImg)){
                StringBuffer headImgSb = new StringBuffer();
                headImgSb.append(headImg).insert(4,"s");
                authorizerInfoMap.put("headImg",headImgSb);
            }else{
                authorizerInfoMap.put("headImg",null);
            }
            authorizerInfoMap.put("userName",authorizerInfo.getString("user_name"));
            authorizerInfoMap.put("signature",authorizerInfo.getString("signature"));
            authorizerInfoMap.put("principalName",authorizerInfo.getString("principal_name"));
            authorizerInfoMap.put("businessInfo",authorizerInfo.getString("business_info"));
            authorizerInfoMap.put("qrcodeUrl",authorizerInfo.getString("qrcode_url"));
            authorizerInfoMap.put("MiniProgramInfo",authorizerInfo.getString("MiniProgramInfo"));
            if (!StringUtils.isEmpty(authorizerInfo.getString("MiniProgramInfo"))){
                if ("0".equals(status)){
                    //获取所有类目
                    List categoryList = getcategory(authorizationType);
                    authorizerInfoMap.put("getcategory",categoryList);
                }
            }
            if (StringUtils.isEmpty(authorizerInfo.getString("MiniProgramInfo"))){
                authorizerInfoMap.put("authorizationUrl","https://console.yooruan.com/h5/?appId="+wechatAuthorizationInfo.getAuthorizerAppid());
            }
            authorizerInfoMap.put("appid",wechatAuthorizationInfo.getAuthorizerAppid());
            authorizerInfoMap.put("authorizerStatus",0);
            String funcInfoObj = authorizationInfo.getString("func_info");
            if (!StringUtils.isEmpty(funcInfoObj)){
                JSONArray funcInfoArray= JSONArray.parseArray(funcInfoObj);
                Long[] funcInfoId = new Long[funcInfoArray.size()];
                for (int i = 0; i < funcInfoArray.size(); i++) {
                    Object funcscopeCategory = funcInfoArray.getJSONObject(i).get("funcscope_category");
                    JSONObject funcscopeCategoryObj = JSONObject.parseObject(String.valueOf(funcscopeCategory));
                    String id = funcscopeCategoryObj.getString("id");
                    funcInfoId[i] = Long.parseLong(id);
                }
                QueryWrapper<WechatFuncInfo> queryWrapper = new QueryWrapper<>();
                queryWrapper.in("funcInfo_id",funcInfoId);
                queryWrapper.select("funcInfo_name");
                List<WechatFuncInfo> wechatFuncInfoList = wechatFuncInfoMapper.selectList(queryWrapper);
                authorizerInfoMap.put("funcInfo",wechatFuncInfoList);
            }

        }

//        JSONObject jsonObject = new JSONObject(authorizerInfoMap);
//        logger.info("授权方信息=>"+jsonObject);
        return authorizerInfoMap;
    }


    /**
     * 获取小程序基本信息
     */
    private final static String getaccountbasicinfo = "https://api.weixin.qq.com/cgi-bin/account/getaccountbasicinfo?access_token=";
    @Override
    public WechatAppletInfo getAppletInfo(String authorizationType) {
        //查询授权信息
        WechatAuthorizationInfo wechatAuthorizationInfo = getAuthorizerAppid(authorizationType);
        String appletInfoReturnJSon = HttpUtil.get(getaccountbasicinfo + wechatAuthorizationInfo.getAuthorizerAccessToken());
        logger.info("获取小程序基本信息返回参数=>"+appletInfoReturnJSon);
        JSONObject obj = JSONObject.parseObject(appletInfoReturnJSon);
        //存入数据库
        WechatAppletInfo wechatAppletInfo = new WechatAppletInfo(obj.getLong("errcode"),obj.getString("errmsg"),
                obj.getString("appid"),obj.getInteger("account_type"),obj.getInteger("principal_type"),
                obj.getString("principal_name"),obj.getString("credential"),obj.getString("realname_status"),
                obj.getString("wx_verify_info"),obj.getString("signature_info"),obj.getString("head_image_info"),
                obj.getString("nickname_info"),obj.getLong("registered_country"),DateUtil.date());
        wechatAppletInfoMapper.insert(wechatAppletInfo);
        if (!StringUtils.isEmpty(appletInfoReturnJSon)){
            logger.info("成功存入数据库,返回参数为=>"+wechatAppletInfo);
        }else {
            logger.info("小程序返回参数信息存入数据库失败");
        }
        return wechatAppletInfo;
    }

    /**
     * 设置服务器域名
     * @param action 操作类型
     * @return
     */
    private final static String modifyDomainApi = "https://api.weixin.qq.com/wxa/modify_domain?access_token=";
    @Override
    public String modifyDomain(String action,String platformid,String authorizationType) {
        if (StringUtils.isEmpty(action)){
            throw new WechatException("操作类型不能为空");
        }
        //查询授权信息
        Object authorizerAppid =  redisService.getCacheObject(CachePrefix.PLATFORM_AUTHORIZER_APPID+platformid+"_"+authorizationType);
        if (authorizerAppid==null){
            QueryWrapper<WechatAuthorizationInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("PLATFORM_ID",platformid);
            queryWrapper.eq("AUTHORIZER_TYPE",authorizationType);
            WechatAuthorizationInfo authorizationInfo = authorizationInfoMapper.selectOne(queryWrapper);
            authorizerAppid = authorizationInfo.getAuthorizerAppid();
        }
        WechatAuthorizationInfo wechatAuthorizationInfo = authorizationInfoMapper.selectById(String.valueOf(authorizerAppid));
        //        WechatAuthorizationInfo wechatAuthorizationInfo = getAuthorizerAppid();
        ServerDomain serverDomain = new ServerDomain();
        serverDomain.setAction(action);
        String[] requestdomain = new String[1];
        requestdomain[0] = WechatMiniService.requestdomain;
//        requestdomain[1] = WechatMiniService.requestdomain;
        serverDomain.setRequestdomain(requestdomain);
        String[] wsrequestdomain = new String[1];
        wsrequestdomain[0] = WechatMiniService.wsrequestdomain;
//        wsrequestdomain[1] = WechatMiniService.wsrequestdomain;
        serverDomain.setWsrequestdomain(wsrequestdomain);
        String[] uploaddomain = new String[1];
        uploaddomain[0] = WechatMiniService.uploaddomain;
//        uploaddomain[1] = WechatMiniService.uploaddomain;
        serverDomain.setUploaddomain(uploaddomain);
        String[] downloaddomain = new String[4];
        downloaddomain[0] = WechatMiniService.downloaddomain;
        downloaddomain[1] = WechatMiniService.downloaddomainTwo;
        downloaddomain[2] = WechatMiniService.downloaddomainThree;
        downloaddomain[3] = WechatMiniService.downloaddomainFour;
        serverDomain.setDownloaddomain(downloaddomain);
        String json =  JSON.toJSONString(serverDomain);
        logger.info("请求参数为=>"+json);
        String modifyDomainRetuen =  HttpUtil.post(modifyDomainApi + wechatAuthorizationInfo.getAuthorizerAccessToken(),json);
        JSONObject obj = JSONObject.parseObject(modifyDomainRetuen);
        logger.info("设置服务器域名返回值:"+obj);
        String errcode = obj.getString("errcode");
        String errmsg = obj.getString("errmsg");
        WechatCommonRetuen commonRetuen = new WechatCommonRetuen();
        commonRetuen.setErrcode(Long.parseLong(errcode));
        commonRetuen.setErrmsg(errmsg);
        HashMap retuenMap = new HashMap();
        retuenMap.put("requestdomain",obj.getString("requestdomain"));
        retuenMap.put("wsrequestdomain",obj.getString("wsrequestdomain"));
        retuenMap.put("uploaddomain",obj.getString("uploaddomain"));
        retuenMap.put("downloaddomain",obj.getString("downloaddomain"));
        JSONObject jsonObj=new JSONObject(retuenMap);
        commonRetuen.setRetuenParameter(String.valueOf(jsonObj));
        wechatCommonRetuenMapper.insert(commonRetuen);
        return errcode;
    }

    /**
     * 设置业务域名
     * @param action 操作类型
     * @return
     */
    private final static String setwebviewdomainApi = "https://api.weixin.qq.com/wxa/setwebviewdomain?access_token=";
    @Override
    public String setwebviewdomain(String action,String platformid,String authorizationType) {
        //查询授权信息
        //查询授权信息
        Object authorizerAppid =  redisService.getCacheObject(CachePrefix.PLATFORM_AUTHORIZER_APPID+platformid+"_"+authorizationType);
        if (authorizerAppid==null){
            QueryWrapper<WechatAuthorizationInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("PLATFORM_ID",SecurityUtils.getPlatformId());
            queryWrapper.eq("AUTHORIZER_TYPE",authorizationType);
            WechatAuthorizationInfo authorizationInfo = authorizationInfoMapper.selectOne(queryWrapper);
            authorizerAppid = authorizationInfo.getAuthorizerAppid();
        }
        WechatAuthorizationInfo wechatAuthorizationInfo = authorizationInfoMapper.selectById(String.valueOf(authorizerAppid));
        BusinessDomain businessDomain = new BusinessDomain();
        if (!StringUtils.isEmpty(action)){
            businessDomain.setAction(action);
        }
        String[] webviewdomain = new String[2];
        webviewdomain[0] = WechatMiniService.webviewdomain;
        webviewdomain[1] = WechatMiniService.webviewdomain;
        businessDomain.setWebviewdomain(webviewdomain);
        String json =  JSON.toJSONString(businessDomain);
        logger.info("请求参数为=>"+json);
        String setwebviewdomainRetuen =  HttpUtil.post(setwebviewdomainApi + wechatAuthorizationInfo.getAuthorizerAccessToken(),json);
        JSONObject obj = JSONObject.parseObject(setwebviewdomainRetuen);
        logger.info("设置业务域名返回值:"+obj);
        WechatCommonRetuen commonRetuen = new WechatCommonRetuen();
        commonRetuen.setErrcode(Long.parseLong(obj.getString("errcode")));
        commonRetuen.setErrmsg(obj.getString("errmsg"));
        wechatCommonRetuenMapper.insert(commonRetuen);
        return obj.getString("errcode");
    }

    /**
     * 绑定体验者
     */
    private final static String bind_tester = "https://api.weixin.qq.com/wxa/bind_tester?access_token=";
    @Override
    public String bindTester(String wechatid,String authorizationType) {
        if (StringUtils.isEmpty(wechatid)){
            throw new WechatException("微信号不能为空");
        }
        //查询授权信息
        WechatAuthorizationInfo wechatAuthorizationInfo = getAuthorizerAppid(authorizationType);
        String param = "{"+"\"wechatid\":\""+wechatid+"\""+"}";
        logger.info("请求参数为=>"+param);
        String bindTestRetuen =  HttpUtil.post(bind_tester + wechatAuthorizationInfo.getAuthorizerAccessToken(),param);
        JSONObject obj = JSONObject.parseObject(bindTestRetuen);
        String errcode = obj.getString("errcode");
        String errmsg = obj.getString("errmsg");
        String userstr = obj.getString("userstr");
        WechatCommonRetuen commonRetuen = new WechatCommonRetuen();
        commonRetuen.setErrcode(Long.parseLong(errcode));
        commonRetuen.setErrmsg(errmsg);
        commonRetuen.setRetuenParameter(userstr);
        wechatCommonRetuenMapper.insert(commonRetuen);
        return obj.getString("errcode");
    }

    /**
     * 获取体验者列表
     * @return
     */
    private final static String memberauthApi = "https://api.weixin.qq.com/wxa/memberauth?access_token=";
    @Override
    public String getmemberauthList(String authorizationType) {
        //查询授权信息
        WechatAuthorizationInfo wechatAuthorizationInfo = getAuthorizerAppid(authorizationType);
        String param = "{"+"\"action\":\"get_experiencer\""+"}";
        logger.info("请求参数为=>"+param);
        String unbindTestRetuen =  HttpUtil.post(memberauthApi + wechatAuthorizationInfo.getAuthorizerAccessToken(),param);
        JSONObject obj = JSONObject.parseObject(unbindTestRetuen);
        if ("0".equals(obj.getString("errcode"))){
            WechatCommonRetuen commonRetuen = new WechatCommonRetuen();
            commonRetuen.setErrcode(Long.parseLong(obj.getString("errcode")));
            commonRetuen.setErrmsg(obj.getString("errmsg"));
            commonRetuen.setRetuenParameter(obj.getString("members"));
            wechatCommonRetuenMapper.insert(commonRetuen);
        }
        return obj.getString("members");
    }

    /**
     * 解除绑定体验者
     */
    private final static String unbind_tester = "https://api.weixin.qq.com/wxa/unbind_tester?access_token=";
    @Override
    public String unbindTester(String wechatid,String authorizationType) {
        //查询授权信息
        WechatAuthorizationInfo wechatAuthorizationInfo = getAuthorizerAppid(authorizationType);
        String param = "{"+"\"wechatid\":\""+wechatid+"\""+"}";
        logger.info("请求参数为=>"+param);
        String unbindTestRetuen =  HttpUtil.post(unbind_tester + wechatAuthorizationInfo.getAuthorizerAccessToken(),param);
        JSONObject obj = JSONObject.parseObject(unbindTestRetuen);
        WechatCommonRetuen commonRetuen = new WechatCommonRetuen();
        commonRetuen.setErrcode(Long.parseLong(obj.getString("errcode")));
        commonRetuen.setErrmsg(obj.getString("errmsg"));
        commonRetuen.setRetuenParameter(wechatid);
        wechatCommonRetuenMapper.insert(commonRetuen);
        return obj.getString("errcode");
    }

    /**
     * 设置名称
     * @param nickName
     * @param idCard
     * @param license
     * @return
     */
    private final static String setnicknameApi = "https://api.weixin.qq.com/wxa/setnickname?access_token=";
    @Override
    public String setAppletName(String nickName,String media_id,String authorizationType) {
        //查询授权信息
        WechatAuthorizationInfo wechatAuthorizationInfo = getAuthorizerAppid(authorizationType);
        String paramJson = "{\"nick_name\": \""+nickName+"\",\"license\": \""+media_id+"\"}";
        logger.info("请求参数为=>"+paramJson);
        String setnicknameRetuen =  HttpUtil.post(setnicknameApi + wechatAuthorizationInfo.getAuthorizerAccessToken(),paramJson);
        JSONObject obj = JSONObject.parseObject(setnicknameRetuen);
        logger.info("设置名称返回值:"+obj);
        return obj.getString("errcode");
    }

    /**
     * 修改头像
     * @param headImgMediaId
     * @param x1
     * @param y1
     * @param x2
     * @param y2
     * @return
     */
    private final static String modifyheadimageApi = "https://api.weixin.qq.com/cgi-bin/account/modifyheadimage?access_token=";
    @Override
    public String modifyheadimage(String headImgMediaId, String x1, String y1, String x2, String y2,String authorizationType) {
        //查询授权信息
        WechatAuthorizationInfo wechatAuthorizationInfo = getAuthorizerAppid(authorizationType);
        String paramJson = "{\"head_img_media_id\": \""+headImgMediaId+"\",\"x1\": \""+x1+"\",\"y1\": \""+y1+"\",\"x2\": \""+x2+"\",\"y2\": \""+y2+"\"}";
        logger.info("请求参数为=>"+paramJson);
        String modifyheadimageApiRetuen =  HttpUtil.post(modifyheadimageApi + wechatAuthorizationInfo.getAuthorizerAccessToken(),paramJson);
        JSONObject obj = JSONObject.parseObject(modifyheadimageApiRetuen);
        WechatCommonRetuen commonRetuen = new WechatCommonRetuen();
        commonRetuen.setErrcode(Long.parseLong(obj.getString("errcode")));
        commonRetuen.setErrmsg(obj.getString("errmsg"));
        wechatCommonRetuenMapper.insert(commonRetuen);
        return obj.getString("errcode");
    }

    /**
     * 修改简介
     */
    private final static String modifysignatureApi = "https://api.weixin.qq.com/cgi-bin/account/modifysignature?access_token=";
    @Override
    public String modifysignature(String signature,String authorizationType) {
        WechatAuthorizationInfo authorizerInfo = getAuthorizerAppid(authorizationType);
        Map<String,Object> param = new HashMap<>();
        param.put("signature",signature);
        logger.info("请求参数为=>"+param);
        String modifysignatureRetuen =  HttpUtil.post(modifysignatureApi + authorizerInfo.getAuthorizerAccessToken(),JSON.toJSONString(param));
        JSONObject obj = JSONObject.parseObject(modifysignatureRetuen);
        WechatCommonRetuen commonRetuen = new WechatCommonRetuen();
        commonRetuen.setErrcode(Long.parseLong(obj.getString("errcode")));
        commonRetuen.setErrmsg(obj.getString("errmsg"));
        wechatCommonRetuenMapper.insert(commonRetuen);
        return obj.getString("errcode");
    }

    /**
     * 获取代码模板列表
     * @param templateType 0（对应普通模板）和1(对应标准模板),如果不填，则返回全部
     * @return template_list [create_time:创建时间,user_version:模板版本号
     * user_desc：模板描述,template_id:模板 id,template_type:0对应普通模板，1对应标准模板]
     */
    private final static String gettemplatelistApi = "https://api.weixin.qq.com/wxa/gettemplatelist?access_token=";
    @Override
    public CodeTemplateVo gettemplatelist(String templateType,String authorizationType) {
        //查询授权信息
        WechatAuthorizationInfo wechatAuthorizationInfo = getAuthorizerAppid(authorizationType);
        Map<String,Object> param = new HashMap<>();
        param.put("template_type",""+templateType+"");
        JSONObject paramJson = new JSONObject(param);
        logger.info("请求参数为=>"+paramJson);
        String gettemplatelistRetuen =  HttpUtil.get(gettemplatelistApi + wechatPlatformService.getApiComponentToken(),paramJson);
        JSONObject obj = JSONObject.parseObject(gettemplatelistRetuen);
        String templateListJson =  obj.getString("template_list");
        List<CodeTemplateVo> templateVo = JSONArray.parseArray(templateListJson, CodeTemplateVo.class);
        CodeTemplateVo codeTemplateVo = new CodeTemplateVo();
        codeTemplateVo.setTemplate_id(0L);
        for (CodeTemplateVo template:templateVo){
//            Long Tid = template.getTemplate_id();
            Long createTime = template.getCreate_time();
            logger.info("模板创建时间为=>"+createTime+"版本号为=>"+template.getUser_version());
            if (codeTemplateVo.getCreate_time() == null || createTime > codeTemplateVo.getCreate_time()){
                codeTemplateVo.setTemplate_id(template.getTemplate_id());
                codeTemplateVo.setUser_version(template.getUser_version());
                codeTemplateVo.setTemplate_type(template.getTemplate_type());
                codeTemplateVo.setCreate_time(template.getCreate_time());
            }
        }
        logger.info("========返回模板信息:模板id:"+codeTemplateVo.getTemplate_id()+";模板类型:"+codeTemplateVo.getTemplate_type()+";模板版本号:"+codeTemplateVo.getUser_version()+"");

        return codeTemplateVo;
    }

    /**
     * 修改模板版本号
     * @param
     */
    @Override
    public void updateTemplateVersion(CodeTemplateVo templateVo,String authorizationType ) {
        //查询授权信息
        WechatAuthorizationInfo wechatAuthorizationInfo = getAuthorizerAppid(authorizationType);
        WechatAuthorizationInfo authorizerappid = authorizationInfoMapper.selectById(wechatAuthorizationInfo.getAuthorizerAppid());
        if (authorizerappid.getTemplateVersion()!=null){
            if (!authorizerappid.getTemplateVersion().equals(templateVo.getUser_version())){
                authorizerappid.setTemplateVersion(templateVo.getUser_version());
                authorizationInfoMapper.updateById(authorizerappid);
            }
        }
    }

    /**
     * 上传代码
     * @param templateId 代码模板id
     * @return
     */
    private final static String uploadCodeApi = "https://api.weixin.qq.com/wxa/commit?access_token=";
    @Override
    public String uploadCode(String templateId, String templateType,String userVersion,String userDesc,String authorizationType,Boolean funcType) {
        WechatAuthorizationInfo authorizerInfo = getAuthorizerAppid(authorizationType);
        //ext_json
        String TemplateJson = null;
        //extJson
        HashMap extMap = new HashMap();
        extMap.put("appid",authorizerInfo.getAuthorizerAppid());
        JSONObject extJson=new JSONObject(extMap);
        //获取店铺名称
        R<PlatformInfoVo> platformR = remotePlatformService.getPlatform(SecurityUtils.getPlatformId());
        PlatformInfoVo platformInfoVo = platformR.getData();
        if ("0".equals(templateType)){
            OrdinaryTemplate ordinaryTemplate = new OrdinaryTemplate();
            ordinaryTemplate.setExtAppid(authorizerInfo.getAuthorizerAppid());
            ordinaryTemplate.setExt(extJson);
            if(funcType == true){
                String[] expages = new String[2];
                expages[0] = "\"pages/Home/Home\": {\"navigationBarTitleText\": \""+platformInfoVo.getPlatformName()+"\",\"usingComponents\": {\"tabbar\": \"/components/tabbar\",\"u-load-err\": \"/uview-ui/components/u-load-err/u-load-err\",\"home-temp\": \"/pages/Home/homeTemp\",\"show-coupon\": \"/pages/Home/showCoupon\",\"pro-s-k-u-detail\": \"/pages/productDetail/proSKUDetail\",\"home-behavior\": \"/pages/productDetail/showUserBehavior\",\"refresh\": \"/components/refresh\",\"pendant\": \"plugin-private://wx2b03c6e691cd7370/components/pendant/pendant\"}}";
                expages[1] = "\"pages/productDetail/productDetail\": {\"usingComponents\": {\"u-icon\": \"/uview-ui/components/u-icon/u-icon\",\"u-image\": \"/uview-ui/components/u-image/u-image\",\"u-load-err\": \"/uview-ui/components/u-load-err/u-load-err\",\"pro-banner\": \"/pages/productDetail/proBanner\",\"pro-price-type\": \"/pages/productDetail/proPriceType\",\"pro-comment\": \"/pages/productDetail/proComment\",\"pro-detail-content\": \"/pages/productDetail/proDetailContent\",\"pro-s-k-u-detail\": \"/pages/productDetail/proSKUDetail\",\"pro-coupon\": \"/pages/productDetail/getProCoupon\",\"share-box\": \"/pages/productDetail/shareBox\",\"show-product-params\": \"/pages/productDetail/showProductParams\",\"show-user-behavior\": \"/pages/productDetail/showUserBehavior\",\"pro-unpay-box\": \"/pages/productDetail/proUnpayBox\",\"packages-box\": \"/pages/productDetail/packagesBox\",\"loading\": \"/components/loading\",\"guess-like\": \"/components/guessLike\",\"pendant\": \"plugin-private://wx2b03c6e691cd7370/components/pendant/pendant\"}}";
                ordinaryTemplate.setExtPages(expages);
                String[] plugin = new String[1];
                plugin[0] = "\"live-player-plugin\": {\"version\": \"1.3.2\",\"provider\": \"wx2b03c6e691cd7370\"}";
                ordinaryTemplate.setPlugin(plugin);
            }else{
                String[] expages = new String[1];
                expages[0] = "\"pages/Home/Home\": { \"navigationBarTitleText\": \""+platformInfoVo.getPlatformName()+"\"}";
                ordinaryTemplate.setExtPages(expages);
                ordinaryTemplate.setPlugin(new String[0]);
            }
            ordinaryTemplate.setWindow("{\"navigationBarTitleText\": \""+platformInfoVo.getPlatformName()+"\"}");
            ordinaryTemplate.setNetworkTimeout(new String[0]);
            ordinaryTemplate.setTabBar(new String[0]);
            TemplateJson =  JSON.toJSONString(ordinaryTemplate);
        }
        if ("1".equals(templateType)){
            StandardTemplate standardTemplate = new StandardTemplate();
            standardTemplate.setExtAppid(authorizerInfo.getAuthorizerAppid());
            standardTemplate.setExt(extJson);
            standardTemplate.setWindow("{\"navigationBarTitleText\": \""+platformInfoVo.getPlatformName()+"\"}");
            TemplateJson = JSON.toJSONString(standardTemplate);
        }
        logger.info("ext_json为=>"+TemplateJson);
        CodeTemplate codeTemplate = new CodeTemplate();
        codeTemplate.setTemplate_id(templateId);
        codeTemplate.setExt_json(TemplateJson);
        codeTemplate.setUser_version(userVersion);
        codeTemplate.setUser_desc(userDesc);
        String codeTemplateJson =  JSON.toJSONString(codeTemplate);
        logger.info("请求参数为=>"+codeTemplateJson);
        String uploadCode =  HttpUtil.post(uploadCodeApi + authorizerInfo.getAuthorizerAccessToken(),codeTemplateJson);
        String uploadCodeRetuen = StringEscapeUtils.unescapeJavaScript(uploadCode);
        logger.info("返回参数为=>"+uploadCodeRetuen);
        JSONObject obj = JSONObject.parseObject(uploadCodeRetuen);
        WechatCommonRetuen commonRetuen = new WechatCommonRetuen();
        commonRetuen.setErrcode(Long.parseLong(obj.getString("errcode")));
        commonRetuen.setErrmsg(obj.getString("errmsg"));
        wechatCommonRetuenMapper.insert(commonRetuen);
        return obj.getString("errcode");
    }

    /**
     * 获取体验版二维码
     * @return
     */
    @Override
    public String getQrcode(String authorizationType)throws IOException{
        WechatAuthorizationInfo authorizerinfo = getAuthorizerAppid(authorizationType);
        String path = URLEncoder.encode("pages/Home/Home","utf-8");
        byte[] getQrcodeRetuen =  HttpUtil.downloadBytes("https://api.weixin.qq.com/wxa/get_qrcode?access_token="+authorizerinfo.getAuthorizerAccessToken()+"&path="+path);
        logger.info("调用获取体验版二维码Api返回=>"+getQrcodeRetuen);
        String rst = Base64.getEncoder().encodeToString(getQrcodeRetuen);
        logger.info("编码为base64=>"+rst);
        return rst;
    }

    /**
     * 设置隐私
     */
    private final static String setprivacysettingApi ="https://api.weixin.qq.com/cgi-bin/component/setprivacysetting?access_token=";
    public String setprivacysetting(String accessToken) {

        Map<String,Object> setting = new HashMap<String,Object>();

        Map<String,String> owner_setting = new HashMap<String,String>();
        owner_setting.put("contact_email","33991786@qq.com");
        owner_setting.put("notice_method","弹窗");

        setting.put("owner_setting",owner_setting);


        List<Map<String,String>> list = new ArrayList<>();
        Map<String,String> userInfoSet = new  HashMap<String,String>();
        userInfoSet.put("privacy_key","UserInfo");//用户信息（微信昵称、头像）
        userInfoSet.put("privacy_text","识别您的身份");
        list.add(userInfoSet);

        Map<String,String> locationSet = new  HashMap<String,String>();
        locationSet.put("privacy_key","Location");//位置信息
        locationSet.put("privacy_text","推荐附近店铺");
        list.add(locationSet);

        Map<String,String> addressSet = new  HashMap<String,String>();
        addressSet.put("privacy_key","Address");//地址
        addressSet.put("privacy_text","快速保存收货地址");
        list.add(addressSet);

        Map<String,String> albumSet = new  HashMap<String,String>();
        albumSet.put("privacy_key","Album");//选中的照片或视频信息
        albumSet.put("privacy_text","分享给好友");
        list.add(albumSet);

        Map<String,String> phoneNumberSet = new  HashMap<String,String>();
        phoneNumberSet.put("privacy_key","PhoneNumber");//手机号码
        phoneNumberSet.put("privacy_text","快速注册账号");
        list.add(phoneNumberSet);

        Map<String,String> albumWriteOnlySet = new  HashMap<String,String>();
        albumWriteOnlySet.put("privacy_key","AlbumWriteOnly");//手机号码
        albumWriteOnlySet.put("privacy_text","保存分享图片");
        list.add(albumWriteOnlySet);


        setting.put("setting_list",list);

        logger.info("请求地址为=>"+setprivacysettingApi + accessToken);
        String jsonParam =  JSON.toJSONString(setting);
        logger.info("请求参数为=>"+jsonParam);

        String submitAuditReturn =  HttpUtil.post(setprivacysettingApi + accessToken,jsonParam);
        logger.info("返回参数为=>"+submitAuditReturn);
        JSONObject obj = JSONObject.parseObject(submitAuditReturn);
        WechatCommonRetuen commonRetuen = new WechatCommonRetuen();
        commonRetuen.setErrcode(Long.parseLong(obj.getString("errcode")));
        commonRetuen.setErrmsg(obj.getString("errmsg"));
        wechatCommonRetuenMapper.insert(commonRetuen);
        return obj.getString("errcode");
    }

    /**
     * 提交审核
     * @return
     */
    private final static String submitAuditApi = "https://api.weixin.qq.com/wxa/submit_audit?access_token=";
    @Override
    public String submitAudit(String userVersion,Boolean releaseType,String authorizationType,Boolean funcType) {
        WechatAuthorizationInfo authorizerInfo = getAuthorizerAppid(authorizationType);
        if (authorizerInfo == null){
            return "获取应用信息失败";
        }
        //设置隐私信息
        setprivacysetting(authorizerInfo.getAuthorizerAccessToken());
        AppletCodeAudit appletCodeAudit = new AppletCodeAudit();
        appletCodeAudit.setItem_list(new String[0]);
        appletCodeAudit.setFeedback_info("");
        appletCodeAudit.setFeedback_stuff("");
        appletCodeAudit.setPreview_info(new String[0]);
        appletCodeAudit.setVersion_desc("");
        appletCodeAudit.setUgc_declare(new String[0]);
        String appletCodeAuditJson =  JSON.toJSONString(appletCodeAudit);
        logger.info("请求参数为=>"+appletCodeAuditJson);
        String submitAuditReturn =  HttpUtil.post(submitAuditApi + authorizerInfo.getAuthorizerAccessToken(),appletCodeAuditJson);
        logger.info("返回参数为=>"+submitAuditReturn);
        JSONObject obj = JSONObject.parseObject(submitAuditReturn);
        WechatCommonRetuen commonRetuen = new WechatCommonRetuen();
        commonRetuen.setErrcode(Long.parseLong(obj.getString("errcode")));
        commonRetuen.setErrmsg(obj.getString("errmsg"));
        commonRetuen.setRetuenParameter(obj.getString("auditid"));
        wechatCommonRetuenMapper.insert(commonRetuen);
        //修改审核状态与发布状态
        WechatAuthorizationInfo wechatAuthorizationInfo = authorizationInfoMapper.selectById(authorizerInfo.getAuthorizerAppid());
        if (releaseType != null){
            wechatAuthorizationInfo.setIssueStatus(String.valueOf(releaseType));
        }
        wechatAuthorizationInfo.setIsIssue(WechatIssueTypeEnum.notIssue.getKey());
        wechatAuthorizationInfo.setTemplateVersion(userVersion);
        wechatAuthorizationInfo.setAuditStatus(WechatAuditStatusEnum.underReview.getKey());
        wechatAuthorizationInfo.setFuncType(String.valueOf(funcType));
        wechatAuthorizationInfo.setUpdateTime(DateUtil.date());
        authorizationInfoMapper.updateById(wechatAuthorizationInfo);
//        WechatAuditInfo auditInfo =  wechatAuditInfoMapper.selectAuditInfo(authorizerInfo.getAuthorizerAppid(),SecurityUtils.getPlatformId());
//        if (auditInfo==null){
//            WechatAuditInfo wechatAuditInfo = new WechatAuditInfo();
//            wechatAuditInfo.setAuthorizerAppid(authorizerInfo.getAuthorizerAppid());
//            wechatAuditInfo.setPlatformId(SecurityUtils.getPlatformId());
//            wechatAuditInfo.setIsIssue(String.valueOf(releaseType));
//            wechatAuditInfoMapper.insert(wechatAuditInfo);
//        }else {
//            auditInfo.setPlatformId(SecurityUtils.getPlatformId());
//
//            auditInfo.setIsIssue(String.valueOf(releaseType));
//            wechatAuditInfoMapper.updateById(auditInfo);
//        }
        return obj.getString("errcode");
    }

    /**
     * 查询最新一次提交的审核状态
     * @return
     */
    private final static String getLatestAuditstatusApi = "https://api.weixin.qq.com/wxa/get_latest_auditstatus?access_token=";
    @Override
    public HashMap getLatestAuditstatus(String authorizationType) {
        WechatAuthorizationInfo authorizerInfo = getAuthorizerAppid(authorizationType);
        String getLatestAuditstatusRetuen =  HttpUtil.get(getLatestAuditstatusApi + authorizerInfo.getAuthorizerAccessToken());
        JSONObject obj = JSONObject.parseObject(getLatestAuditstatusRetuen);
        WechatCommonRetuen commonRetuen = new WechatCommonRetuen();
        commonRetuen.setErrcode(Long.parseLong(obj.getString("errcode")));
        commonRetuen.setErrmsg(obj.getString("errmsg"));
        String auditid = obj.getString("auditid");
        String status = obj.getString("status");
        String reason = obj.getString("reason");
        String ScreenShot = obj.getString("ScreenShot");
        HashMap retuenMap = new HashMap();
        retuenMap.put("auditid",auditid);
        retuenMap.put("status",status);
        retuenMap.put("reason",reason);
        retuenMap.put("ScreenShot",ScreenShot);
        WechatAuthorizationInfo wechatAuthorizationInfo = authorizationInfoMapper.selectById(authorizerInfo.getAuthorizerAppid());
        wechatAuthorizationInfo.setAuditStatus(status);
        wechatAuthorizationInfo.setUpdateTime(DateUtil.date());
        authorizationInfoMapper.updateById(wechatAuthorizationInfo);
//        WechatAuditInfo wechatAuditInfo =  wechatAuditInfoMapper.selectAuditInfo(authorizerInfo.getAuthorizerAppid(),SecurityUtils.getPlatformId());
//        if(wechatAuditInfo!=null){
//            retuenMap.put("isIssue",wechatAuditInfo.getIsIssue());
//        }else {
//            retuenMap.put("isIssue",null);
//        }
        retuenMap.put("isIssue",wechatAuthorizationInfo.getIssueStatus());
        JSONObject jsonObj=new JSONObject(retuenMap);
        commonRetuen.setRetuenParameter(String.valueOf(jsonObj));
        wechatCommonRetuenMapper.insert(commonRetuen);
        return retuenMap;
    }

    /**
     * 审核撤回
     * @return
     */
    private final static String undocodeauditApi = "https://api.weixin.qq.com/wxa/undocodeaudit?access_token=";
    @Override
    public String undocodeaudit(String authorizationType) {
        WechatAuthorizationInfo authorizerInfo = getAuthorizerAppid(authorizationType);
        String undocodeauditRetuen =  HttpUtil.get(undocodeauditApi + authorizerInfo.getAuthorizerAccessToken());
        JSONObject obj = JSONObject.parseObject(undocodeauditRetuen);
        WechatCommonRetuen commonRetuen = new WechatCommonRetuen();
        commonRetuen.setErrcode(Long.parseLong(obj.getString("errcode")));
        commonRetuen.setErrmsg(obj.getString("errmsg"));
        wechatCommonRetuenMapper.insert(commonRetuen);
        return obj.getString("errcode");
    }

    /**
     * 发布已通过审核的小程序
     * @return
     */
    private final static String releaseApi = "https://api.weixin.qq.com/wxa/release?access_token=";
    @Override
    public String release(String appid,String authorizationType) {
        WechatAuthorizationInfo authorizerInfo = null;
        if (!StringUtils.isEmpty(appid)){
            WechatAuthorizationInfo wechatAuthorizationInfo = authorizationInfoMapper.selectById(appid);
            String key = CachePrefix.PLATFORM_AUTHORIZER_APPID+wechatAuthorizationInfo.getPlatformId()+"_"+authorizationType;
            Object authorizerappid = redisService.getCacheObject(key);
            authorizerInfo = authorizationInfoMapper.selectById(String.valueOf(authorizerappid));
            if (authorizerappid != null){
                if("-1".equals(wechatAuthorizationInfo.getDataStatus())){
                    throw new WechatException("请授权后重试");
                }
            }else {
                authorizerInfo = PlatformRefreshToken(authorizationType,wechatAuthorizationInfo.getPlatformId());
            }
        }else {
            authorizerInfo = getAuthorizerAppid(authorizationType);
        }
        String releaseApiRetuen =  HttpUtil.post(releaseApi + authorizerInfo.getAuthorizerAccessToken(),"{}");
        JSONObject obj = JSONObject.parseObject(releaseApiRetuen);
//        WechatCommonRetuen commonRetuen = new WechatCommonRetuen();
//        commonRetuen.setErrcode(Long.parseLong(obj.getString("errcode")));
//        commonRetuen.setErrmsg(obj.getString("errmsg"));
//        wechatCommonRetuenMapper.insert(commonRetuen);
        if ("0".equals(obj.getString("errcode"))){
            WechatAuthorizationInfo wechatAuthorizationInfo = authorizationInfoMapper.selectById(authorizerInfo.getAuthorizerAppid());
            wechatAuthorizationInfo.setAuditStatus(WechatAuditStatusEnum.reviewSuccess.getKey());
            wechatAuthorizationInfo.setIsIssue(WechatIssueTypeEnum.issue.getKey());
            wechatAuthorizationInfo.setIssueTime(DateUtil.date());
            wechatAuthorizationInfo.setUpdateTime(DateUtil.date());
            authorizationInfoMapper.updateById(wechatAuthorizationInfo);
        }
        return obj.getString("errcode");
    }

    /**
     * 版本回退
     * @param appVersion
     * @return
     */
    @Override
    public String revertcoderelease(String appVersion,String authorizationType) {
        WechatAuthorizationInfo authorizerInfo = getAuthorizerAppid(authorizationType);
        String revertcodereleaseRetuen =  HttpUtil.get("https://api.weixin.qq.com/wxa/revertcoderelease?app_version="+appVersion+"&access_token="+authorizerInfo.getAuthorizerAccessToken());
        JSONObject obj = JSONObject.parseObject(revertcodereleaseRetuen);
        WechatCommonRetuen commonRetuen = new WechatCommonRetuen();
        commonRetuen.setErrcode(Long.parseLong(obj.getString("errcode")));
        commonRetuen.setErrmsg(obj.getString("errmsg"));
        wechatCommonRetuenMapper.insert(commonRetuen);
        return obj.getString("errcode");
    }

    /**
     * 设置最低基础库版本
     * @param version
     * @return
     */
    private final static String setweappsupportversionApi = "https://api.weixin.qq.com/cgi-bin/wxopen/setweappsupportversion?access_token=";
    @Override
    public String setweappsupportversion(String version,String authorizationType) {
        WechatAuthorizationInfo authorizerInfo = getAuthorizerAppid(authorizationType);
//        String paramJson = "{\"version\": \""+version+"\"}";
        logger.info("请求参数为"+version);
        String setweappsupportversionRetuen =  HttpUtil.post(setweappsupportversionApi + authorizerInfo.getAuthorizerAccessToken(),version);
        JSONObject obj = JSONObject.parseObject(setweappsupportversionRetuen);
        WechatCommonRetuen commonRetuen = new WechatCommonRetuen();
        commonRetuen.setErrcode(Long.parseLong(obj.getString("errcode")));
        commonRetuen.setErrmsg(obj.getString("errmsg"));
        wechatCommonRetuenMapper.insert(commonRetuen);
        return obj.getString("errcode");
    }

    /**
     * 查询服务商的当月提审限额（quota）和加急次数
     * @return
     */
    private final static String queryquotaApi = "https://api.weixin.qq.com/wxa/queryquota?access_token=";
    @Override
    public String queryquota(String authorizationType) {
        WechatAuthorizationInfo authorizerInfo = getAuthorizerAppid(authorizationType);
        String queryquotaRetuen =  HttpUtil.get(queryquotaApi + authorizerInfo.getAuthorizerAccessToken());
        JSONObject obj = JSONObject.parseObject(queryquotaRetuen);
        WechatCommonRetuen commonRetuen = new WechatCommonRetuen();
        commonRetuen.setErrcode(Long.parseLong(obj.getString("errcode")));
        commonRetuen.setErrmsg(obj.getString("errmsg"));
        String rest = obj.getString("rest");
        String limit = obj.getString("limit");
        String speedupRest = obj.getString("speedup_rest");
        String speedupLimit = obj.getString("speedup_limit");
        HashMap retuenMap = new HashMap();
        retuenMap.put("rest",rest);
        retuenMap.put("limit",limit);
        retuenMap.put("speedupRest",speedupRest);
        retuenMap.put("speedupLimit",speedupLimit);
        JSONObject jsonObj=new JSONObject(retuenMap);
        commonRetuen.setRetuenParameter(String.valueOf(jsonObj));
        wechatCommonRetuenMapper.insert(commonRetuen);
        return obj.getString("errcode");
    }

    /**
     * 加急审核申请
     */
    private final static String speedupauditApi = "https://api.weixin.qq.com/wxa/speedupaudit?access_token=";
    @Override
    public String speedupaudit(String auditid,String authorizationType) {
        WechatAuthorizationInfo authorizerInfo = getAuthorizerAppid(authorizationType);
//        String paramJson = "{\"auditid\": \""+auditid+"\"}";
        logger.info("请求参数为"+auditid);
        String speedupauditRetuen =  HttpUtil.post(speedupauditApi + authorizerInfo.getAuthorizerAccessToken(),auditid);
        JSONObject obj = JSONObject.parseObject(speedupauditRetuen);
        WechatCommonRetuen commonRetuen = new WechatCommonRetuen();
        commonRetuen.setErrcode(Long.parseLong(obj.getString("errcode")));
        commonRetuen.setErrmsg(obj.getString("errmsg"));
        wechatCommonRetuenMapper.insert(commonRetuen);
        return obj.getString("errcode");
    }


    /**
     * 获取已设置的所有类目
     * @return
     */
    private final static String getcategoryApi = "https://api.weixin.qq.com/cgi-bin/wxopen/getcategory?access_token=";
    @Override
    public List getcategory(String authorizationType) {
        WechatAuthorizationInfo authorizerInfo = getAuthorizerAppid(authorizationType);
        String getcategoryReturn =  HttpUtil.get(getcategoryApi + authorizerInfo.getAuthorizerAccessToken());
        JSONObject obj = JSONObject.parseObject(getcategoryReturn);
        WechatCommonRetuen commonRetuen = new WechatCommonRetuen();
        commonRetuen.setErrcode(Long.parseLong(obj.getString("errcode")));
        commonRetuen.setErrmsg(obj.getString("errmsg"));
        commonRetuen.setRetuenParameter(obj.getString("categories")+obj.getString("limit")+obj.getString("quota")+obj.getString("category_limit"));
        wechatCommonRetuenMapper.insert(commonRetuen);
        List<CategoryInfo> categoryInfoList = new ArrayList<>();
        logger.info("类目信息返回=>"+obj);
        if (obj.getString("errcode").equals("0") && !StringUtils.isEmpty(obj.getString("categories"))){
            JSONArray categoriesArr = obj.getJSONArray("categories");
            logger.info("类目集合:"+categoriesArr);
            for (int i = 0; i < categoriesArr.size(); i++) {
                CategoryInfo categoryInfo = new CategoryInfo();
                categoryInfo.setFirst(String.valueOf(categoriesArr.getJSONObject(i).get("first")));
                categoryInfo.setFirstName(String.valueOf(categoriesArr.getJSONObject(i).get("first_name")));
                categoryInfo.setSecond(String.valueOf(categoriesArr.getJSONObject(i).get("second")));
                categoryInfo.setSecondName(String.valueOf(categoriesArr.getJSONObject(i).get("second_name")));
                categoryInfo.setAuditStatus(String.valueOf(categoriesArr.getJSONObject(i).get("audit_status")));
                categoryInfo.setAuditReason(String.valueOf(categoriesArr.getJSONObject(i).get("audit_reason")));
                categoryInfoList.add(categoryInfo);
            }
        }
        return categoryInfoList;
    }

    /**
     * 添加类目
     * @return
     */
    private final static String addcategoryApi = "https://api.weixin.qq.com/cgi-bin/wxopen/addcategory?access_token=";
    @Override
    public String addcategory(String first,String second,String key,String value,String authorizationType) {
        WechatAuthorizationInfo authorizerInfo = getAuthorizerAppid(authorizationType);
        Category category = new Category();
        category.setFirst(first);
        category.setSecond(second);
        Certicates[] certicatesArray = new Certicates[0];
//        Certicates certicates = new Certicates();
//        certicates.setKey(key);
//        certicates.setValue(value);
//        certicatesArray[0] = certicates;
        category.setCerticates(certicatesArray);
        HashMap param = new HashMap();
        Category[] categories = new Category[1];
        categories[0] = category;
        param.put("categories",categories);
        JSONObject paramJson = new JSONObject(param);
        logger.info("请求参数为=>"+paramJson);
        String getcategoryReturn =  HttpUtil.post(getcategoryApi + authorizerInfo.getAuthorizerAccessToken(),paramJson);
        logger.info("添加类目返回值+>"+getcategoryReturn);
        JSONObject obj = JSONObject.parseObject(getcategoryReturn);
        WechatCommonRetuen commonRetuen = new WechatCommonRetuen();
        commonRetuen.setErrcode(Long.parseLong(obj.getString("errcode")));
        commonRetuen.setErrmsg(obj.getString("errmsg"));
        wechatCommonRetuenMapper.insert(commonRetuen);
        return obj.getString("errcode");
    }

    /**
     * 删除类目
     * @param first
     * @param second
     * @return
     */
    private final static String deletecategoryApi = "https://api.weixin.qq.com/cgi-bin/wxopen/deletecategory?access_token=";
    @Override
    public String deletecategory(String first, String second,String authorizationType) {
        WechatAuthorizationInfo authorizerInfo = getAuthorizerAppid(authorizationType);
        String paramJson = "{\"first\": \""+first+"\",\"second\": \""+second+"\"}";
        logger.info("请求参数为"+paramJson);
        String speedupauditRetuen =  HttpUtil.post(deletecategoryApi + authorizerInfo.getAuthorizerAccessToken(),paramJson);
        JSONObject obj = JSONObject.parseObject(speedupauditRetuen);
        WechatCommonRetuen commonRetuen = new WechatCommonRetuen();
        commonRetuen.setErrcode(Long.parseLong(obj.getString("errcode")));
        commonRetuen.setErrmsg(obj.getString("errmsg"));
        wechatCommonRetuenMapper.insert(commonRetuen);
        return obj.getString("errcode");
    }

    /**
     * 获取小程序违规处罚记录
     */
    private final static String getillegalrecordsApi = "https://api.weixin.qq.com/wxa/getillegalrecords?access_token=";
    @Override
    public String getillegalrecords(String authorizationType) {
        WechatAuthorizationInfo authorizerInfo = getAuthorizerAppid(authorizationType);
        String paramJson = "{\"start_time\": \""+null+"\",\"end_time\": \""+null+"\"}";
        logger.info("请求参数为"+paramJson);
        String speedupauditRetuen =  HttpUtil.post(getillegalrecordsApi + authorizerInfo.getAuthorizerAccessToken(),paramJson);
        JSONObject obj = JSONObject.parseObject(speedupauditRetuen);
        logger.info("获取小程序违规处罚记录返回值:"+obj);
//        WechatCommonRetuen commonRetuen = new WechatCommonRetuen();
//        commonRetuen.setErrcode(Long.parseLong(obj.getString("errcode")));
//        commonRetuen.setErrmsg(obj.getString("errmsg"));
//        if (!StringUtils.isEmpty(obj.getString("records"))){
//            JSONArray recordsArr = obj.getJSONArray("records");
//            List<AppletIllegalrecodes> appletIllegalrecodesList = new ArrayList<>();
//            for (int i = 0; i < recordsArr.size(); i++) {
//                JSONObject recordsObj = recordsArr.getJSONObject(i);
//                logger.info("recordsObj=>"+recordsObj);
//                AppletIllegalrecodes appletIllegalrecodes = new AppletIllegalrecodes();
//                appletIllegalrecodes.setIllegalRecordId(recordsObj.getString("illegal_record_id"));
//                Long createTimeTime =  recordsObj.getLong("create_time");
//                SimpleDateFormat format =  new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
//                String d = format.format(createTimeTime);
//                Date date= null;
//                try {
//                    date = format.parse(d);
//                } catch (ParseException e) {
//                    e.printStackTrace();
//                }
//                appletIllegalrecodes.setCreateTime(date);
//                appletIllegalrecodes.setIllegalReason(recordsObj.getString("illegal_reason"));
//                appletIllegalrecodes.setRuleName(recordsObj.getString("rule_name"));
//                appletIllegalrecodes.setRuleUrl(recordsObj.getString("rule_url"));
//                appletIllegalrecodesList.add(appletIllegalrecodes);
//            }
//            commonRetuen.setRetuenParameter(String.valueOf(obj.getJSONArray("records")));
//            wechatCommonRetuenMapper.insert(commonRetuen);
//        }
        return obj.getString("records");
    }

    /**
     * 获取小程序申诉记录
     * @param illegalRecordId
     * @return
     */
    private final static String getappealrecordsApi = "https://api.weixin.qq.com/wxa/getappealrecords?access_token=";
    @Override
    public  List<AppealRecord> getappealrecords(String illegalRecordId,String authorizationType) {
        WechatAuthorizationInfo authorizerInfo = getAuthorizerAppid(authorizationType);
//        String paramJson = "{\"illegal_record_id\": \""+illegalRecordId+"\"}";
        logger.info("请求参数为"+illegalRecordId);
        String speedupauditRetuen =  HttpUtil.post(getappealrecordsApi + authorizerInfo.getAuthorizerAccessToken(),illegalRecordId);
        JSONObject obj = JSONObject.parseObject(speedupauditRetuen);
        WechatCommonRetuen commonRetuen = new WechatCommonRetuen();
        commonRetuen.setErrcode(Long.parseLong(obj.getString("errcode")));
        commonRetuen.setErrmsg(obj.getString("errmsg"));
        JSONArray recordsArr = obj.getJSONArray("records");
        logger.info("申诉记录集合:"+recordsArr);
        List<AppealRecord> appealRecordList = new ArrayList<>();
        if (recordsArr != null){
            for (int i = 0; i < recordsArr.size(); i++) {
                AppealRecord appealRecord = new AppealRecord();
                appealRecord.setAppealRecordId(recordsArr.getJSONObject(i).getLong("appeal_record_id"));
                appealRecord.setAppealTime(recordsArr.getJSONObject(i).getLong("appeal_time"));
                appealRecord.setAppealCount(recordsArr.getJSONObject(i).getLong("appeal_count"));
                appealRecord.setAppealFrom(recordsArr.getJSONObject(i).getLong("appeal_from"));
                appealRecord.setAuditTime(recordsArr.getJSONObject(i).getLong("audit_time"));
                appealRecord.setAuditReason(recordsArr.getJSONObject(i).getLong("audit_time"));
                appealRecord.setAppealStatus(recordsArr.getJSONObject(i).getLong("appeal_status"));
                appealRecord.setPunishDescription(recordsArr.getJSONObject(i).getLong("punish_description"));
                appealRecordList.add(appealRecord);
            }
        }
        commonRetuen.setRetuenParameter(obj.getString("records"));
        wechatCommonRetuenMapper.insert(commonRetuen);
        return appealRecordList;
    }

    /**
     * 获取urllink
     */
    private final static String generateUrllinkApi = "https://api.weixin.qq.com/wxa/generate_urllink?access_token=";
    @Override
    public String generateUrllink(String authorizationType) {
        WechatAuthorizationInfo authorizerInfo = getAuthorizerAppid(authorizationType);
        AppletUrllink appletUrllink = new AppletUrllink();
//        appletUrllink.setPath("/pages/Home/Home");
        appletUrllink.setPath("");
        appletUrllink.setQuery("");
        appletUrllink.setIs_expire(true);
        appletUrllink.setExpire_type(1L);
        appletUrllink.setExpire_interval(1L);
//        appletUrllink.setCloud_base("{}");
        String generateUrllinkJson =  JSON.toJSONString(appletUrllink);
        logger.info("请求参数为"+generateUrllinkJson);
        String generateUrllinkRetuen =  HttpUtil.post(generateUrllinkApi + authorizerInfo.getAuthorizerAccessToken(),generateUrllinkJson);
        JSONObject obj = JSONObject.parseObject(generateUrllinkRetuen);
        WechatCommonRetuen commonRetuen = new WechatCommonRetuen();
        commonRetuen.setErrcode(Long.parseLong(obj.getString("errcode")));
        commonRetuen.setErrmsg(obj.getString("errmsg"));
        commonRetuen.setRetuenParameter(obj.getString("url_link"));
        wechatCommonRetuenMapper.insert(commonRetuen);
        return obj.getString("url_link");
    }

    /**
     * 获取小程序scheme码
     * @return
     */
    private final static String generateschemeApi = "https://api.weixin.qq.com/wxa/generatescheme?access_token=";
    @Override
    public String generatescheme(String authorizationType) {
        WechatAuthorizationInfo authorizerInfo = getAuthorizerAppid(authorizationType);
        AppletScheme appletScheme = new AppletScheme();
        HashMap jumpwxaMap = new HashMap();
//        jumpwxaMap.put("path","/pages/Home/Home");
        jumpwxaMap.put("path","");
        jumpwxaMap.put("query","");
        JSONObject jumpwxaJson=new JSONObject(jumpwxaMap);
        appletScheme.setJump_wxa(jumpwxaJson);
        appletScheme.setIs_expire(false);
//        appletScheme.setExpire_time(0L);
        String appletSchemeJson =  JSON.toJSONString(appletScheme);
        logger.info("请求参数为"+appletSchemeJson);
        String appletSchemeRetuen =  HttpUtil.post(generateschemeApi + authorizerInfo.getAuthorizerAccessToken(),appletSchemeJson);
        JSONObject obj = JSONObject.parseObject(appletSchemeRetuen);
        WechatCommonRetuen commonRetuen = new WechatCommonRetuen();
        commonRetuen.setErrcode(Long.parseLong(obj.getString("errcode")));
        commonRetuen.setErrmsg(obj.getString("errmsg"));
        commonRetuen.setRetuenParameter(obj.getString("openlink"));
        wechatCommonRetuenMapper.insert(commonRetuen);
        return obj.getString("openlink");
    }

    /**
     * 新增临时素材
     * @param type 类型：分别有图片（image）、语音（voice）、视频（video）和缩略图（thumb）
     * @param  file
     * @return
     */
    @Override
    public JSONObject uploadMedia(String type, String platformid,String authorizationType, File file) throws Exception {
        logger.info("新增临时素材当前平台id=>"+platformid+"类型为+"+authorizationType);
        QueryWrapper<WechatAuthorizationInfo> authorizationInfoQueryWrapper = new QueryWrapper<>();
        authorizationInfoQueryWrapper.eq("PLATFORM_ID",platformid);
        authorizationInfoQueryWrapper.eq("AUTHORIZER_TYPE",authorizationType);
        WechatAuthorizationInfo wechatAuditInfo = authorizationInfoMapper.selectOne(authorizationInfoQueryWrapper);
        String materialApi = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token="+wechatAuditInfo.getAuthorizerAccessToken()+"&type="+type;
        HttpPost httpPost = new HttpPost(materialApi);
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
        httpPost.setConfig(requestConfig);

        //2.3 设置请求实体，封装了请求参数
        HttpEntity requestEntity = MultipartEntityBuilder.create().addPart("media",
                new FileBody(file, ContentType.create("multipart/form-data", Consts.UTF_8), file.getName())).build();
        httpPost.setEntity(requestEntity);
        try {
            response = httpClient.execute(httpPost, new BasicHttpContext());
            if (response.getStatusLine().getStatusCode() != 200) {

                logger.info("request url failed, http code=" + response.getStatusLine().getStatusCode()
                        + ", url=" + materialApi);
                return null;
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String resultStr = EntityUtils.toString(entity, "utf-8");
                logger.info("upload result={}",resultStr);
                JSONObject result = JSON.parseObject(resultStr);
                //上传临时素材成功
                if (result.getString("errcode")== null) {
                    // 成功
                    //result.remove("errcode");
                    //result.remove("errmsg");
                    return result;
                } else {
                    logger.info("request url=" + materialApi + ",return value=");
                    logger.info(resultStr);
                    int errCode = result.getInteger("errcode");
                    String errMsg = result.getString("errmsg");
                    throw new Exception("error code:"+errCode+", error message:"+errMsg);
                }
            }
        } catch (IOException e) {
            logger.info("request url=" + materialApi + ", exception, msg=" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();                  //释放资源
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    /**
     * 获取临时素材
     * @param mediaId
     * @return
     */
    @Override
    public String getTemporaryMaterial(String mediaId,String authorizationType) {
        WechatAuthorizationInfo authorizerInfo = getAuthorizerAppid(authorizationType);
        String getTemporaryMaterialRetuen =  HttpUtil.get("https://api.weixin.qq.com/cgi-bin/media/get?access_token="+authorizerInfo.getAuthorizerAccessToken()+"&media_id="+mediaId);
        logger.info("返回参数为"+getTemporaryMaterialRetuen);
        return getTemporaryMaterialRetuen;
    }

    @Override
    public String setPaymentType(String merchantID,String authorizationType) {
        Object authorizerAppid =  redisService.getCacheObject(CachePrefix.PLATFORM_AUTHORIZER_APPID+ SecurityUtils.getPlatformId());
        if (StringUtils.isEmpty(authorizerAppid)){
            QueryWrapper<WechatAuthorizationInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("PLATFORM_ID",SecurityUtils.getPlatformId());
            queryWrapper.eq("AUTHORIZER_TYPE",authorizationType);
            WechatAuthorizationInfo authorizationInfo = authorizationInfoMapper.selectOne(queryWrapper);
            authorizerAppid = authorizationInfo.getAuthorizerAppid();
        }
        WechatAuthorizationInfo wechatAuthorizationInfo = authorizationInfoMapper.selectById(String.valueOf(authorizerAppid));
        wechatAuthorizationInfo.setMerchantId(merchantID);
        authorizationInfoMapper.updateById(wechatAuthorizationInfo);
        return "0";
    }

    /**
     * 处理审核结果
     * @param
     * @param
     * @param
     */
    @Override
    public Boolean updateAuditInfo(Boolean issueStatus,String appid,String authorizationType) {
        logger.info("===当前"+appid+"==自动发布状态:"+issueStatus+"");

        if (issueStatus == true){
            //代码发布
            String releaseRst = release(appid,authorizationType);
            if ("0".equals(releaseRst)){
                return true;
            }else {
                return false;
            }
        }
        return true;
    }

    /**
     * 获取可设置的所有类目
     * @return
     */
    private final static String getallcategoriesApi = "https://api.weixin.qq.com/cgi-bin/wxopen/getallcategories?access_token=";
    @Override
    public List<CanSetCategoryInfoVo> getallcategories(String authorizationType) {
        WechatAuthorizationInfo authorizerInfo = getAuthorizerAppid(authorizationType);
        String getallcategoriesRetuen =  HttpUtil.get(getallcategoriesApi + authorizerInfo.getAuthorizerAccessToken());
        JSONObject obj = JSONObject.parseObject(getallcategoriesRetuen);
        WechatCommonRetuen commonRetuen = new WechatCommonRetuen();
        commonRetuen.setErrcode(Long.parseLong(obj.getString("errcode")));
        commonRetuen.setErrmsg(obj.getString("errmsg"));
        String categoryListStr = obj.getString("categories_list");
        JSONObject categoryListObj = JSONObject.parseObject(categoryListStr);
        JSONArray categoriesArr = categoryListObj.getJSONArray("categories");
        List<CanSetCategoryInfo> categoryInfoList = new ArrayList<>();
        List<CanSetCategoryInfoVo> canSetCategoryInfoVos = new ArrayList<>();
        HashMap categoryMap = new HashMap();
        for (int i = 0; i < categoriesArr.size(); i++) {
            if ("0".equals(categoriesArr.getJSONObject(i).getString("sensitive_type"))){
//                logger.info("类目信息=>"+categoriesArr.getJSONObject(i));
                CanSetCategoryInfo canSetCategoryInfo = new CanSetCategoryInfo();
                Long id = categoriesArr.getJSONObject(i).getLong("id");
                String name = categoriesArr.getJSONObject(i).getString("name");
                Long level = categoriesArr.getJSONObject(i).getLong("level");
                Long father = categoriesArr.getJSONObject(i).getLong("father");
                String childrenJsonstr = categoriesArr.getJSONObject(i).getString("children");
                if (level == 1){
                    categoryInfoList.add(new CanSetCategoryInfo(id, level,name, father,childrenJsonstr));
                }
                if (level>1){
                    categoryMap.put(id,name);
                }
            }
        }
        for (CanSetCategoryInfo categoryInfo:categoryInfoList){
            CanSetCategoryInfoVo canSetCategoryInfovo = new CanSetCategoryInfoVo();
            if (categoryInfo!=null){
                canSetCategoryInfovo.setValue(categoryInfo.getId());
            }else {
                canSetCategoryInfovo.setValue(null);
            }
            canSetCategoryInfovo.setLabel(categoryInfo.getName());
            String children = categoryInfo.getChildren();
//            logger.info("children=>"+children);
            String childrenSubstring = children.substring(1, children.length() - 1);
            List<CanSetCategoryInfoVo> canSetCategoryInfoVoList = new ArrayList<>();
            if (!StringUtils.isEmpty(childrenSubstring)){
                Object name = new Object();
                String[] childrenSubstringSplit = childrenSubstring.split(",");
                for (int i = 0; i < childrenSubstringSplit.length; i++) {
                    CanSetCategoryInfoVo canSetCategoryInfo = new CanSetCategoryInfoVo();
                    name = categoryMap.get(Long.parseLong(childrenSubstringSplit[i]));
                    if (name!=null){
                        canSetCategoryInfo.setValue(Long.parseLong(childrenSubstringSplit[i]));
                        canSetCategoryInfo.setLabel(String.valueOf(name));
                        canSetCategoryInfoVoList.add(canSetCategoryInfo);
                    }
                }
                canSetCategoryInfovo.setChildren(canSetCategoryInfoVoList);
                if (name != null){
                    canSetCategoryInfoVos.add(canSetCategoryInfovo);
                }
            }
        }
        wechatCommonRetuenMapper.insert(commonRetuen);
        return canSetCategoryInfoVos;
    }

    @Override
    public HashMap isBind(String authorizationType) {
        logger.info("判断平台:"+SecurityUtils.getPlatformId()+",类型为："+authorizationType+"是否绑定");
        QueryWrapper<WechatAuthorizationInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PLATFORM_ID",SecurityUtils.getPlatformId());
        queryWrapper.eq("AUTHORIZER_TYPE",authorizationType);
        queryWrapper.eq("DATA_STATUS", DataStatus.valid.getKey());
        WechatAuthorizationInfo authorizationInfo = authorizationInfoMapper.selectOne(queryWrapper);
        HashMap map = new HashMap();
        if (authorizationInfo!=null){
            map.put("authorizationStatus","0");
            map.put("authorizerAppid",authorizationInfo.getAuthorizerAppid());
            map.put("merchantId",authorizationInfo.getMerchantId());
            map.put("authorizerType",authorizationInfo.getAuthorizerType());
            map.put("issueStatus",authorizationInfo.getIssueStatus());
            map.put("issueTime",authorizationInfo.getIssueTime());
            map.put("auditStatus",authorizationInfo.getAuditStatus());
            map.put("templateVersion",authorizationInfo.getTemplateVersion());
            CodeTemplateVo gettemplatelist = gettemplatelist(null, authorizationType);
            if(gettemplatelist != null){
                map.put("newTemplateVersion",gettemplatelist.getUser_version());
            }
            map.put("funcType",authorizationInfo.getFuncType());
            map.put("isIssue",authorizationInfo.getIsIssue());
            map.put("businessCode",authorizationInfo.getBusinessCode());
            map.put("isExchangebind",authorizationInfo.getIsExchangeBind());
        }else {
            map.put("authorizationStatus","-1");
        }
        return map;
    }

    /**
     * 获取小程序码
     */
    private final static String getwxacodeunlimitApi = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=";
    @Override
    public String getwxacodeunlimit(WxQrCode wxQrCode){
        String uploadBytes = null;
        String keyCode = null;
        String key = CachePrefix.PLATFORM_AUTHORIZER_APPID+wxQrCode.getPlatformId()+"_"+wxQrCode.getAuthorizationType();
        Object authorizerappid = redisService.getCacheObject(key);
        WechatAuthorizationInfo wechatAuthorizationInfo = authorizationInfoMapper.selectById(String.valueOf(authorizerappid));
        if (authorizerappid != null){
            if("-1".equals(wechatAuthorizationInfo.getDataStatus())){
                throw new WechatException("请授权后重试");
            }
        }else {
            wechatAuthorizationInfo = PlatformRefreshToken(wxQrCode.getAuthorizationType(),String.valueOf(wxQrCode.getPlatformId()));
        }
        Long proId = wxQrCode.getProId();
        String scene = new String();
        String page = new String();
        if (proId != null && ObjectUtil.isEmpty(SecurityUtils.getCustomerUid())) {
            scene = "proId=" + proId + ";userId=0";
            page = "pages/productDetail/productDetail";
        } else if(wxQrCode.getSharecustomerUid() != null){
            scene = "sharecustomerUid=" + wxQrCode.getSharecustomerUid()+";";
            page = "pages/Home/Home";
        }else{
            //redisService
            keyCode = CachePrefix.WECHAT_CODE_PRODUCT + proId + SecurityUtils.getCustomerUid();
            scene = "proId=" + proId + ";userId=" + SecurityUtils.getCustomerUid();
            page = "pages/productDetail/productDetail";
            uploadBytes = redisService.get(keyCode,String.class);
            if(ObjectUtil.isNotEmpty(uploadBytes)) return uploadBytes;
        }
        HashMap<String, Object> map = new HashMap();
        map.put("scene", scene);
        map.put("page", page);
        String stringMap = JSON.toJSONString(map);
        logger.info("请求参数为"+stringMap);
        byte[] inputStream = null;
        try {
//            WeixinQrCodeUtil.post(getwxacodeunlimitApi + wechatAuthorizationInfo.getAuthorizerAccessToken(),stringMap,"20200904");
            inputStream = WeixinQrCodeUtil.httpsRequest(getwxacodeunlimitApi + wechatAuthorizationInfo.getAuthorizerAccessToken(), "POST", stringMap);
            logger.info("inputStream=>"+inputStream);
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(inputStream);
            if (byteArrayInputStream.available() <= 200) {
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                int i;
                byte[] buffer = new byte[200];
                while ((i = byteArrayInputStream.read(buffer)) != -1) {
                    byteArrayOutputStream.write(buffer, 0, i);
                }
                String str = new String(byteArrayOutputStream.toByteArray());
                JSONObject jsonObject = new JSONObject().parseObject(str);
                logger.info("jsonObject=>"+jsonObject);
                if ("41030".equals(jsonObject.getString("errcode")) || "40001".equals(jsonObject.getString("errcode"))) {
                    throw new WechatException("所传page页面不存在,或者小程序没有发布");
                } else if ("45009".equals(jsonObject.getString("errcode"))) {
                    throw new WechatException("调用分钟频率受限");
                }
                byteArrayOutputStream.close();
            }
            byteArrayInputStream.close();
            //保存图片
            String filename = "wxcode" + "_" + System.currentTimeMillis() + ".png";
            uploadBytes = WeixinQrCodeUtil.uploadBytes(filename,inputStream);
            logger.info("保存图片返回=>"+uploadBytes);
            if(ObjectUtil.isNotEmpty(keyCode)) redisService.set(keyCode,uploadBytes,30L,TimeUnit.DAYS);
            return uploadBytes;
        }catch (Exception e) {
            e.printStackTrace();
            throw new WechatException("所传page页面不存在,或者小程序没有发布");
        }
    }

    /**
     * 查询当前平台的授权信息
     * @return
     */
    public WechatAuthorizationInfo getAuthorizerAppid(String authorizationType){
        String key = CachePrefix.PLATFORM_AUTHORIZER_APPID+ SecurityUtils.getPlatformId()+"_"+authorizationType;
        Object authorizerappid = redisService.getCacheObject(key);
        WechatAuthorizationInfo wechatAuthorizationInfo = authorizationInfoMapper.selectById(String.valueOf(authorizerappid));
        if (authorizerappid != null){
            logger.info("=========获取到缓存信息"+authorizerappid+"==================");
            if(wechatAuthorizationInfo!=null){
                if("-1".equals(wechatAuthorizationInfo.getDataStatus())){
                    throw new WechatException("请授权后重试");
                }
            }else{
                throw new WechatException("未授权,请授权后重试");
            }
            return wechatAuthorizationInfo;
        }else {
            WechatAuthorizationInfo authorizationInfo = refreshToken(authorizationType);
            return authorizationInfo;
        }

    }

    //刷新令牌(指定平台)
    public WechatAuthorizationInfo PlatformRefreshToken(String authorizationType,String platformid){
        String appidKey = CachePrefix.PLATFORM_AUTHORIZER_APPID+ platformid+"_"+authorizationType;
//        WechatAuthorizationInfo wechatAuthorizationInfo = new WechatAuthorizationInfo();
        //查询授权信息
        QueryWrapper<WechatAuthorizationInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PLATFORM_ID",platformid);
        queryWrapper.eq("AUTHORIZER_TYPE",authorizationType);
        queryWrapper.eq("DATA_STATUS",DataStatus.valid.getKey());
        WechatAuthorizationInfo authorizationInfo = authorizationInfoMapper.selectOne(queryWrapper);
        //调用刷新令牌
        if (authorizationInfo!=null){
            logger.info("Appid:"+authorizationInfo.getAuthorizerAppid()+"==刷新令牌:"+authorizationInfo.getAuthorizerRefreshToken());
            AuthorizationInfoVo apiAuthorizer = wechatPlatformService.getApi_authorizer_token(wechatPlatformService.getApiComponentToken(), authorizationInfo.getAuthorizerAppid(), authorizationInfo.getAuthorizerRefreshToken());
            Long expiresIn = apiAuthorizer.getExpires_in();
            authorizationInfo.setAuthorizerAccessToken(apiAuthorizer.getAuthorizer_access_token());
            authorizationInfo.setAuthorizerRefreshToken(apiAuthorizer.getAuthorizer_refresh_token());
            authorizationInfo.setExpiresIn(expiresIn);
            authorizationInfo.setUpdateTime(DateUtil.date());
            authorizationInfoMapper.updateById(authorizationInfo);
            redisService.expire(appidKey, expiresIn,TimeUnit.SECONDS);
            logger.info("Appid为:"+authorizationInfo.getAuthorizerAppid()+":token过期已重新刷新");
            return authorizationInfo;
        }else{
            throw new WechatException("请授权后重试");
        }
    }

    //刷新令牌
    @Override
    public WechatAuthorizationInfo refreshToken(String authorizationType){
        String appidKey = CachePrefix.PLATFORM_AUTHORIZER_APPID+ SecurityUtils.getPlatformId()+"_"+authorizationType;
//        WechatAuthorizationInfo wechatAuthorizationInfo = new WechatAuthorizationInfo();
        //查询授权信息
        logger.info("刷新令牌查看授权信息当前平台id=>"+SecurityUtils.getPlatformId()+"当前类型"+authorizationType);
        QueryWrapper<WechatAuthorizationInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PLATFORM_ID",SecurityUtils.getPlatformId());
        queryWrapper.eq("AUTHORIZER_TYPE",authorizationType);
        queryWrapper.eq("DATA_STATUS",DataStatus.valid.getKey());
        WechatAuthorizationInfo authorizationInfo = authorizationInfoMapper.selectOne(queryWrapper);
        //调用刷新令牌
        if (authorizationInfo!=null){
            logger.info("Appid:"+authorizationInfo.getAuthorizerAppid()+"==刷新令牌:"+authorizationInfo.getAuthorizerRefreshToken());
            AuthorizationInfoVo apiAuthorizer = wechatPlatformService.getApi_authorizer_token(wechatPlatformService.getApiComponentToken(), authorizationInfo.getAuthorizerAppid(), authorizationInfo.getAuthorizerRefreshToken());
            Long expiresIn = apiAuthorizer.getExpires_in()-1800;
            authorizationInfo.setAuthorizerAccessToken(apiAuthorizer.getAuthorizer_access_token());
            authorizationInfo.setAuthorizerRefreshToken(apiAuthorizer.getAuthorizer_refresh_token());
            authorizationInfo.setExpiresIn(expiresIn);
            authorizationInfo.setUpdateTime(DateUtil.date());
            authorizationInfoMapper.updateById(authorizationInfo);
            redisService.setCacheObject(appidKey,authorizationInfo.getAuthorizerAppid(),expiresIn,TimeUnit.SECONDS);
//            redisService.expire(appidKey, expiresIn,TimeUnit.SECONDS);
            logger.info("Appid为:"+authorizationInfo.getAuthorizerAppid()+":token过期已重新刷新");
            return authorizationInfo;
        }else{
            throw new WechatException("请授权后重试");
        }
    }

    @Override
    public Boolean saveAuthorizationInfo(WechatAuthorizationInfoVo wechatAuthorizationInfoVo) {
        WechatAuthorizationInfo wechatAuthorizationInfo = new WechatAuthorizationInfo();
        BeanUtils.copyProperties(wechatAuthorizationInfoVo,wechatAuthorizationInfo);
        //新增主键
        int expire = 0;
        long L = System.currentTimeMillis();
        redisService.set(WECHAT_H5_AUTHORIZATION,L);
        redisService.incr(WECHAT_H5_AUTHORIZATION,expire);
        String Id =  redisService.getCacheObject(WECHAT_H5_AUTHORIZATION);
        String appid = "h5" + String.valueOf(Id);
        wechatAuthorizationInfo.setAuthorizerAppid(appid);
        wechatAuthorizationInfo.setCreateTime(DateUtil.date());
        wechatAuthorizationInfo.setDataStatus(DataStatus.valid.getKey());
        authorizationInfoMapper.insert(wechatAuthorizationInfo);
        return true;
    }

    /**
     * 查询当前平台指定类型信息
     * @param wechatAuthorizationInfoVo
     * @return
     */
    @Override
    public WechatAuthorizationInfoVo getAuthorizationInfoByPlatform(WechatAuthorizationInfoVo wechatAuthorizationInfoVo) {
        QueryWrapper<WechatAuthorizationInfo> authorizationInfoQueryWrapper = new QueryWrapper<>();
        authorizationInfoQueryWrapper.eq("PLATFORM_ID",wechatAuthorizationInfoVo.getPlatformId());
        authorizationInfoQueryWrapper.eq("AUTHORIZER_TYPE",wechatAuthorizationInfoVo.getAuthorizerType());
        authorizationInfoQueryWrapper.eq("DATA_STATUS",DataStatus.valid.getKey());
        WechatAuthorizationInfo wechatAuthorizationInfo = authorizationInfoMapper.selectOne(authorizationInfoQueryWrapper);
        WechatAuthorizationInfoVo authorizationInfoVo = new WechatAuthorizationInfoVo();
        BeanUtils.copyProperties(wechatAuthorizationInfo,authorizationInfoVo);
        return authorizationInfoVo;
    }


}




